package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.config.ConfigFile;
import com.fwtai.tool.ToolClient;
import com.fwtai.web.PartnerDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 合伙人业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2021-08-02 15:26:31
 * @官网 <url>http://www.fwtai.com</url>
 */
@Service
public class PartnerService{

  private final PartnerDao partnerDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  private final static Long role_province = 498276858366795796L;//省分公司-角色id

  private final static Long role_city = 498276858366795794L;//市分公司-角色id

  private final static Long role_county = 498276858366795792L;//区级代理-角色id

  public PartnerService(final PartnerDao partnerDao,final ThreadPoolTaskExecutor taskExecutor){
    this.partnerDao = partnerDao;
    this.taskExecutor = taskExecutor;
  }

  //审核
  public String edit(final HttpServletRequest request){
    final PageFormData formData = new PageFormData(request);
    final String p_user_id = "user_id";
    final String p_kid = "kid";
    final String p_auth_status = "auth_status";
    final String p_details = "details";
    final String p_confirm = "confirm";
    final String p_type = "type";
    final String validate = ToolClient.validateField(formData,p_auth_status,p_details,p_user_id,p_type);
    if(validate != null)return validate;
    final String fieldInteger = ToolClient.validateInteger(formData,p_auth_status,p_type);
    if(fieldInteger != null)return fieldInteger;
    final String details = formData.getString(p_details);
    if(details.length() > 512){
      return ToolClient.createJsonFail("审核信息太长");
    }
    if(details.startsWith("88888888")){
      return ToolClient.createJsonFail("认证信息有误");
    }
    final Long userId = formData.getLong(p_user_id);
    final Long kid = formData.getLong(p_kid);
    final Long exist_key = partnerDao.queryExistById(userId);
    if(exist_key == null){
      return ToolClient.createJsonFail("数据不存在,刷新重试");
    }
    final int type = formData.getInteger(p_type);//代理区域类型
    final Long provinceId = formData.getLong("provinceId");
    final Long cityId = formData.getLong("cityId");
    final Long countyId = formData.getLong("countyId");
    final Integer auth_status = formData.getInteger(p_auth_status);
    if(auth_status == 2){
      switch (type){
        case 1:
          final Long type1 = partnerDao.getAuditExist(provinceId);
          if(type1 != null){
            return ToolClient.createJsonFail("此区域为特殊区域，请手动绑定");
          }
        case 2:
          final Long type2 = partnerDao.getAuditExist(cityId);
          if(type2 != null){
            return ToolClient.createJsonFail("此区域为特殊区域，请手动绑定");
          }
        case 3:
          final Long type3 = partnerDao.getAuditExist(countyId);
          if(type3 != null){
            return ToolClient.createJsonFail("此区域为特殊区域，请手动绑定");
          }
      }
    }
    //是否是自己已是其他区域的代理，一个账号只能代理一个区域并做提示
    final Integer confirm = formData.getInteger(p_confirm);
    if(auth_status == 2){
      if(confirm == null){//确认操作
        final List<Integer> self = partnerDao.getProxySelf(userId);
        if(self != null && self.size() > 0){
          return ToolClient.createJsonFail("审核失败,当前账号已成功申请其他区域或门店");
        }
        /*final Long exist = partnerDao.getExistProxy(userId,type,provinceId,cityId,countyId);
        if(exist != null){
          return ToolClient.createJsonFail("审核失败,当前账号已成功申请其他区域");
        }*/
        //是否是当前区域的唯一代理,查询该申请人所申请的区域是否有存在代理
        switch(type){
          case 1:
            final boolean proxy1 = partnerDao.getTypeProxy(provinceId);
            if(proxy1){
              return ToolClient.jsonCode198("操作失败,已存在相同省分公司");
            }
            break;
          case 2:
            final boolean proxy2 = partnerDao.getTypeProxy(provinceId,cityId);
            if(proxy2){
              return ToolClient.jsonCode198("操作失败,已存在相同市分公司");
            }
            break;
          case 3:
            final boolean proxy3 = partnerDao.getTypeProxy(provinceId,cityId,countyId);
            if(proxy3){
              return ToolClient.jsonCode198("操作失败,已存在相同区代理");
            }
            break;
          default:
            break;
        }
        //查询是否有上级
        final String invitationUser = partnerDao.getParentReferrer(userId);//邀请人
        if(invitationUser != null && invitationUser.length() == 0){
          return ToolClient.createJsonFail("审核失败,当前申请人已被其他成功邀请");
        }
        //查询推荐人是否有推荐人且是事业部成员
        final Integer vip = partnerDao.getReferrerAndVip(kid);
        if(vip != null && vip == 1){
          final HashMap<String,Object> partnerReferrer = partnerDao.getPartnerReferrer(kid);
          if(partnerReferrer != null){
            return ToolClient.json198(partnerReferrer);
          }
        }
      }
      if(confirm != null){
        //根据
        final HashMap<String,Object> partnerReferrer = partnerDao.getPartnerReferrer(kid);
        return handlerType(partnerReferrer,kid);//第2次确认
      }else{
        //绑定上下级关系,申请人绑定给推荐
        final String code = partnerDao.getPartnerCode(kid);//邀请人,获取临时邀请码,是否可能为空？存在邀请码说明是有人邀请的!
        final boolean bn = code != null;
        if(bn){
          formData.put("invitation_code",code);
          formData.put("relationUserId",userId);
        }
        return ToolClient.executeRows(partnerDao.editOk(formData,bn,getRoleType(type)));//含有推荐人
      }
    }
    return ToolClient.executeRows(partnerDao.edit(formData,getRoleType(type)));
  }

  public Long getRoleType(final int type){
    switch (type){
      case 1:
        return role_province;
      case 2:
        return role_city;
      case 3:
        return role_county;
      default:
        return null;
    }
  }

  //验证事业部用户所邀请的合伙人(代理人)所在地区的省是否已邀请其他合伙人,同一个省仅保留行政区域最大级别
  private String handlerType(final HashMap<String,Object> partnerReferrer,final Long kid){
    final Integer v = (Integer)partnerReferrer.get("type");//查询申请人的推荐人在该地区邀请的代理类型
    final Integer type = (Integer)partnerReferrer.get("proxyType");//代理类型
    final Long proxykid = (Long)partnerReferrer.get("kid");//代理类型
    final PageFormData formData = new PageFormData();
    formData.put("auth_status",2);
    formData.put("kid",kid);
    switch (type){
      case 1:
        if(v == 2 || v == 3){
          return ToolClient.executeRows(partnerDao.editEmptyPartner(proxykid,formData,getRoleType(type)),"审核成功","审核失败");
        }
        break;
      case 2:
        if(v == 1){
          return ToolClient.executeRows(partnerDao.editEmptyPartner(formData,kid,getRoleType(type)),"审核成功","审核失败");
        }else{
          return ToolClient.executeRows(partnerDao.editEmptyPartner(proxykid,formData,getRoleType(type)),"审核成功","审核失败");
        }
      case 3:
        if(v == 1 || v == 2){
          return ToolClient.executeRows(partnerDao.editEmptyPartner(formData,kid,getRoleType(type)),"审核成功","审核失败");

        }else{
          return ToolClient.executeRows(partnerDao.editEmptyPartner(proxykid,formData,getRoleType(type)),"审核成功","审核失败");
        }
      default:
        break;
    }
    return ToolClient.createJsonFail("审核失败");
  }

  public String queryById(final PageFormData formData){
    final String p_id = "id";
    final String validate = ToolClient.validateField(formData,p_id);
    if(validate != null)return validate;
    return ToolClient.queryJson(partnerDao.queryById(formData.getString(p_id)));
  }

  public String listData(PageFormData formData){
    try {
      formData = ToolClient.dataTableMysql(formData);
      if(formData == null)return ToolClient.jsonValidateField();
      final HashMap<String,Object> map = partnerDao.listData(formData);
      return ToolClient.dataTableOK((List<Object>)map.get(ConfigFile.rows),map.get(ConfigFile.total));
    } catch (Exception e){
      return ToolClient.dataTableException(formData.get("sEcho"));
    }
  }

  public String editProtocol(final Long kid,final Integer target){
    if(kid == null || target == null) return ToolClient.jsonValidateField();
    final PageFormData formData = new PageFormData();
    formData.put("user_id",kid);
    formData.put("target",target);
    return ToolClient.executeRows(partnerDao.editProtocol(formData));
  }

  public String getUserType(final String word){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(word == null || word.length() <= 0){
          return ToolClient.jsonCode198("请输入关键字搜索");
        }
        return ToolClient.queryJson(partnerDao.getUserType(word));
      } catch (final Exception ignored){
        return ToolClient.exceptionJson();
      }
    },taskExecutor).join();
  }

  public String addUserType(final Long kid,final Long inviter,final Long userId,final int target){
    return CompletableFuture.supplyAsync(()->{
      if(inviter != null && userId != null){
        if(inviter.equals(userId)){
          return ToolClient.createJsonFail("不能是同一个账号");
        }
      }
      final PageFormData formData = new PageFormData();
      if(target == 1){
        if(inviter != null){
          final String code = partnerDao.getShareParent(inviter);
          if(code == null){
            return ToolClient.createJsonFail("指定的上级代理尚未生成邀请码");
          }
          formData.put("inviter",inviter);//邀请人
          formData.put("userId",userId);//本人kid
          final List<HashMap<String,Object>> partnerProxy = partnerDao.getPartnerProxy(formData);
          if(partnerProxy.size() != 2){
            return ToolClient.createJsonFail("指定账号是无效的邀请人");
          }
          final HashMap<String,Integer> map = new HashMap<>(partnerProxy.size());
          for(int i = partnerProxy.size() - 1; i >= 0; i--){
            final HashMap<String,Object> hashMap = partnerProxy.get(i);
            final String _userId = (String)hashMap.get("userId");
            final boolean _inviter = _userId.equals("inviter");//邀请人
            map.put(_inviter ? "inviter" : "userId",(Integer)hashMap.get("type"));
          }
          final Integer type1 = map.get("userId");
          final Integer type2 = map.get("inviter");
          if(type1 <= type2){
            return ToolClient.createJsonFail("请指定有效上级代理");
          }
          return ToolClient.executeRows(partnerDao.addUserInviter(formData));//走的sys_user
        }
        return ToolClient.executeRows(partnerDao.editUserInviter(userId));//走的sys_user,置空
      }
      if(target == 2){
        formData.put("kid",kid);//合伙人表partner的kid
        formData.put("referrer",userId);//推荐人
        return ToolClient.executeRows(partnerDao.addUserReferrer(formData));//走的partner
      }
      return ToolClient.jsonValidateField();
    },taskExecutor).join();
  }
}